﻿using Brc_DSB.GetWay.Configuration;
using Brc_DSB.GetWay.DataBase;
using Ocelot.Logging;
using Ocelot.Middleware;
using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Brc_DSB.GetWay.Extention;
using System.IO;
using System.Net.Http;
using Ocelot.Middleware.Pipeline;
using Microsoft.AspNetCore.Http;
using System.Reflection;
using System.Collections;
using Ocelot.Headers;
using Ocelot.Configuration.Creator;

namespace Brc_DSB.GetWay.Middleware
{
    public static class WebServiceMiddlewareExtensions
    {
        public static IOcelotPipelineBuilder UseWebServiceMiddleware(this IOcelotPipelineBuilder builder)
        {
            return builder.UseMiddleware<WebServiceMiddleware>();
        }
    }
    public class WebServiceMiddleware : OcelotMiddleware
    {
        private readonly OcelotRequestDelegate _next;
        private readonly DbConfiguration _options;
        private readonly IWebServiceRepository _service;
        private readonly IAddHeadersToRequest _addHeadersToRequest;
        public WebServiceMiddleware(OcelotRequestDelegate next,
            IOcelotLoggerFactory loggerFactory,
            IWebServiceRepository service,
            DbConfiguration options, IAddHeadersToRequest addHeadersToRequest) : base(loggerFactory.CreateLogger<WebServiceMiddleware>())
        {
            _next = next;
            _service = service;
            _options = options;
            _addHeadersToRequest = addHeadersToRequest;
        }


        public async Task Invoke(DownstreamContext context)
        {
            if (!context.IsError && context.HttpContext.Request.Method.ToUpper() != "OPTIONS")
            {
                var upStreamPath = context.HttpContext.Request.Path;
                var pathArray = upStreamPath.Value.TrimStart('/').Split("/");
                var serviceName = pathArray[0];
                var serviceInfo = await _service.GetService(serviceName);
                if (serviceInfo != null)
                {
                    var className = pathArray[1];
                    var methodName = pathArray[2];
                    //var headerList = new List<AddHeader>()
                    //{
                    //    new AddHeader("ClassName",className),
                    //    new AddHeader("MethodName",methodName),
                    //    new AddHeader("ServiceAddress",serviceInfo.ServiceAddress)
                    //};
                    //_addHeadersToRequest.SetHeadersOnDownstreamRequest(headerList, context.DownstreamRequest.);
                    context.DownstreamRequest.Headers.Add("ClassName", className);
                    context.DownstreamRequest.Headers.Add("MethodName", methodName);
                    context.DownstreamRequest.Headers.Add("ServiceAddress", serviceInfo.ServiceAddress);
                }
                await _next.Invoke(context);
            }
        }
    }
}
